package main

import (
	"fmt"
	"github.com/spf13/viper"
	"log"
	"sync"
	"yundian/internel/app/models/orders"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/wechatpay"
)

func main()  {
	dingo.InitViper("./configs/admin.yaml")
	dbs.NewMysqlComponent().Step()

	var wg sync.WaitGroup
	var lock sync.Mutex
	for i := 1; i<= 15; i++ {
		wg.Add(1)
		go func(i int) {
			lock.Lock()
			defer wg.Done()
			taskOrdersTake(i, "./cmd/grawl/data/takeorders/20210123")
			lock.Unlock()
		}(i)
	}

	wg.Wait()
}

func taskOrdersTake(i int, path string)  {
	lists := new(orderTakeGenerated)
	viper.SetConfigFile(fmt.Sprintf(path + "/%d.json", i))
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("viper.ReadInConfig failed : ", err.Error())
	}
	// 反序列化到struct
	if err := viper.Unmarshal(lists); err != nil {
		log.Fatal("viper.Unmarshal failed : ", err.Error())
	}

	// 写入数据库
	var ucount,ccount int
	for _,lst := range lists.Body.Data {
		var tradeState, tradeStateDesc, desc string
		switch lst.State {
		case 1:
			tradeState = "CREATED"  // CREATED 商户已创建服务订单
			tradeStateDesc = "商户已创建服务订单"
		case 2:
			tradeState = "DOING" // DOING 服务订单进行中
			tradeStateDesc = "服务订单进行中"
			desc = "USER_CONFIRM"
		case 5:
			tradeState = "DONE"
			tradeStateDesc = "服务订单完成" // DONE 服务订单完成
			desc = "MCH_COMPLETE"
		case 3:
			tradeState = "REVOKED"
			tradeStateDesc = "商户取消服务订单"    // REVOKED 商户取消服务订单
		case 4:
			tradeState = "EXPIRED" // EXPIRED 服务订单已失效
			tradeStateDesc = "服务订单已失效"
		}

		var payFrom int8
		if lst.TradeType == "Normal" {
			payFrom = 2
		}
		if lst.TradeType == "PreAuthPay" {
			payFrom = 1
		}

		//m := &orders.OrderTakeModel{}
		m := orders.New()
		m.Appid = lst.AppID
		m.Mchid = "1600369044"

		m.TradeNo = lst.TradeNo
		//m.OutTradeNo = lst.ExternalTradeNo
		m.TradeType = lst.TradeType
		m.TradeState = tradeState
		m.TradeStateDesc = tradeStateDesc
		m.TradeStateDoing = desc
		m.State = int8(lst.State)

		m.Title = lst.Title

		m.DeviceSn = lst.DeviceSn
		m.SharedMode = lst.SharedMode
		m.FeeMode = int8(lst.FeeMode)

		m.Money = int64(lst.Money)
		m.MoneyStr = lst.MoneyStr
		m.PayMoney = int64(lst.PayMoney)
		m.PayMoneyStr = lst.PayMoneyStr
		m.SettlementWay = int8(lst.SettlementWay)
		m.SettlementMoney = int64(lst.SettlementMoney)
		m.SettlementMoneyStr = lst.SettlementMoneyStr
		m.SettlementState = int8(lst.SettlementState)
		//m.RefundMoney = int64(lst.RefundMoney)

		m.CouponType = 1
		m.CouponMoney = int64(lst.CouponMoney)
		m.CouponMoneyStr = lst.CouponMoneyStr

		m.OrderFrom = "weixin"
		m.PayType = int8(lst.PayType)  // 3 微信支付
		m.PayFrom = payFrom

		m.PlaceId = lst.PlaceID
		m.PlaceName = lst.PlaceName
		m.MemberId = lst.MemberID
		m.MemberName = lst.MemberName
		m.UserId = lst.PlaceUserID
		m.UserName = lst.PlaceUserName

		m.OvertimeState = int8(lst.OvertimeState)
		m.IsDelete = 0
		m.IsDraw = 1

		m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))
		m.DrawAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.PayAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.EndAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))

		m.ParentId = 100000
		m.ProductId = lst.ProductID

		m.RefundMoney = int64(lst.RefundMoney)

		// 查询 库中是否存在此数据
		var count int64
		global.Orm.Table("orders").Where("trade_no = ?", m.TradeNo).Count(&count)
		if count > 0 {
			ucount++
			global.Orm.Table("orders").Where("trade_no = ?", m.TradeNo).Model(&m).Updates(m)
		} else { // 新增
			ccount++
			global.Orm.Table("orders").Create(m)
		}
	}
	fmt.Printf("当前页-%d,新增%d条,更新%d条 \n", i, ccount, ucount)
}

type orderTakeGenerated struct {
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			TradeNo         string `json:"tradeNo"`
			ProjectID       int    `json:"projectId"`
			AppID           string `json:"appId"`
			Title           string `json:"title"`
			MemberID        string `json:"memberId"`
			MemberName      string `json:"memberName"`
			Money           int    `json:"money"`
			PayType         int    `json:"payType"`
			TradeType       string `json:"tradeType"`
			FeeMode         int    `json:"feeMode"`
			CouponMoney     int    `json:"couponMoney"`
			SettlementWay   int    `json:"settlementWay"`
			SettlementMoney int    `json:"settlementMoney"`
			SettlementState int    `json:"settlementState"`
			PlaceID         int    `json:"placeId"`
			PlaceUserID     int    `json:"placeUserId"`
			PlaceName       string `json:"placeName"`
			PlaceUserName   string `json:"placeUserName"`
			PlaceImgPath    string `json:"placeImgPath"`
			DeviceSn        string `json:"deviceSn"`
			DeviceTypeID    int    `json:"deviceTypeId"`
			SharedMode      string `json:"sharedMode"`
			ProductID       string `json:"productId"`
			OvertimeState   int    `json:"overtimeState"`
			State           int    `json:"state"`
			DelFlag         bool   `json:"delFlag"`
			UpdateDate      string `json:"updateDate"`
			CreateDate      string `json:"createDate"`
			Price               int    `json:"price"`
			PayTypeName         string `json:"payTypeName"`
			PayMoneyStr         string `json:"payMoneyStr"`
			SharedModeName      string `json:"sharedModeName"`
			StateName           string `json:"stateName"`
			FeeModeName         string `json:"feeModeName"`
			CouponMoneyStr      string `json:"couponMoneyStr"`
			OvertimeStateName   string `json:"overtimeStateName"`
			SettlementStateName string `json:"settlementStateName"`
			SettlementMoneyStr  string `json:"settlementMoneyStr"`
			MoneyStr            string `json:"moneyStr"`
			TradeState          int    `json:"tradeState"`
			PayMoney int `json:"payMoney,omitempty"`
			RefundMoney int `json:"refundMoney,omitempty"`
			Agent struct {
				ID               int    `json:"id"`
				RoleType         int    `json:"roleType"`
				LevelType        int    `json:"levelType"`
				Status           int    `json:"status"`
				ProfitType       int    `json:"profitType"`
				ProfitProportion int    `json:"profitProportion"`
				WxIncomeQrcode   string `json:"wxIncomeQrcode"`
				AgentChildCount  int    `json:"agentChildCount"`
				PlaceCount       int    `json:"placeCount"`
				DeviceCount      int    `json:"deviceCount"`
				SettingInfo      string `json:"settingInfo"`
				FunctionSetting  string `json:"functionSetting"`
				ParentID         int    `json:"parentId"`
				RootID           int    `json:"rootId"`
				LeftNum          int    `json:"leftNum"`
				RightNum         int    `json:"rightNum"`
				UpdateDate       string `json:"updateDate"`
				CreateDate       string `json:"createDate"`
				UserID           int    `json:"userId"`
				RoleTypeName     string `json:"roleTypeName"`
				AgentCount       int    `json:"agentCount"`
				HaveChild        bool   `json:"haveChild"`
				IsMain           bool   `json:"isMain"`
				IsLeaf           bool   `json:"isLeaf"`
				IsRoot           bool   `json:"isRoot"`
			} `json:"agent,omitempty"`
		} `json:"data"`
	} `json:"body"`
}
